package com.cmhk.taglib

import com.cmhk.ding.DingAuthService

class DDConfigTagLib {

    DingAuthService dingAuthService
    static namespace = "dd"
    static defaultEncodeAs = [taglib: 'none']

    def config = { attrs, body ->
        def dingtalkConfig = getGrailsApplication().config.dingtalk.oapi
        def agentId = assertAttributes("agentId", attrs, "config")
        def nonceStr = assertAttributes("nonceStr", attrs, "config")
        def jsApiList = assertAttributes("jsApiList", attrs, "config")
        def url = request.getRequestURL().toString()
        def timeStamp = System.currentTimeMillis()
        out << """
                dd.config({
                    agentId: '${agentId}',
                    corpId: '${dingtalkConfig.corpid}',
                    timeStamp:${timeStamp},
                    nonceStr: '${nonceStr}',
                    signature: '${dingAuthService.getSign(nonceStr, timeStamp, url)}',
                    jsApiList: [${jsApiList.collect { "'${it}'" }.join(',')}]
                })

        """
    }

    def cropid = { attrs, body ->
        def dingtalkConfig = getGrailsApplication().config.dingtalk.oapi
        out << dingtalkConfig.corpid
    }

    protected assertAttributes(String name, attrs, String tag) {
        if (!attrs.containsKey(name)) {
            throwTagError "Tag [$tag] is missing required attribute [$name]"
        }
        attrs.remove name
    }

}
